/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.registration.web;

import com.registration.ManagedBean;
import com.registration.core.*;
import com.registration.membership.Member;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.faces.component.UIParameter;
import javax.faces.event.ActionEvent;
import static org.apache.commons.lang.StringUtils.isBlank;
import org.springframework.context.MessageSource;

/**
 *
 * @author Usuario
 */
public class AttendeeBean extends ManagedBean {

    protected MessageSource messageSource;
    private Attendee attendee;
    private String searchValue;
    private String searchType = "CONFIRMATION";
    private List<Country> countries;
    private List<Category> categories;
    private List<Hotel> hotels;
    private String firstName;
    private String middleName;
    private String lastName;
    private String secondLastName;
    private Member member;
    private String message;
    private boolean needVerificationCode = false;
    private List<Attendee> heads;
    private List<Attendee> leaders;
    private List<PaymentMethod> paymentMethods;
    private List<RoomPlan> roomPlans;

    public AttendeeBean() {
    }

    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public void reset() {
        attendee = null;
        searchValue = null;
        searchType = "CONFIRMATION";
        super.reset();
    }

    @Override
    public String cancel() {
        return "success";
    }

    @Override
    public String startup(ActionEvent e) {
        reset();
        UIParameter param = (UIParameter) e.getComponent().getChildren().get(0);
        Long id = (Long) param.getValue();
        
        attendee = getManager().loadAttendee(id);
        countries = getManager().findCountries();
        categories = getManager().findCategories(false);
        hotels = getManager().findHotels();
        heads = getManager().findHeads();
        leaders = getManager().findLeaders();
        paymentMethods = getManager().findPaymentMethods();
        roomPlans = getManager().findRoomPlans();
        return "success";
    }
    
    public String init() {
        reset();
        attendee = new Attendee();
        countries = getManager().findCountries();
        categories = getManager().findCategories(false);
        hotels = getManager().findHotels();
        heads = getManager().findHeads();
        leaders = getManager().findLeaders();
        paymentMethods = getManager().findPaymentMethods();
        roomPlans = getManager().findRoomPlans();
        return "success";
    }

    public String execute() {
        countries = getManager().findCountries();
        categories = getManager().findCategories(false);
        hotels = getManager().findHotels();
        heads = getManager().findHeads();
        leaders = getManager().findLeaders();
        paymentMethods = getManager().findPaymentMethods();
        roomPlans = getManager().findRoomPlans();

        attendee = null;

        if (!isBlank(searchType)) {
            if (searchType.equals("MEMBER_ID")) {
                if (!isBlank(searchValue)) {
                    attendee = getManager().loadAttendeeByMemberId(searchValue, null);
                } else {
                    message = messageSource.getMessage("parameters.required", null, Locale.getDefault());
                    addErrorMessage(message);
                    return "fail";
                }
            }
            if (searchType.equals("CONFIRMATION")) {
                if (!isBlank(searchValue)) {
                    attendee = getManager().loadAttendeeByConfirmation(searchValue, null);
                } else {
                    message = messageSource.getMessage("parameters.required", null, Locale.getDefault());
                    addErrorMessage(message);
                    return "fail";
                }
            }
            if (searchType.equals("NAME")) {
                if (!isBlank(firstName) || !isBlank(middleName) || !isBlank(lastName) || !isBlank(secondLastName)) {
                    List<Attendee> attendees = getManager().findAttendees(firstName, middleName, lastName, secondLastName, null, "", "", null, null, null);
                    if (attendees != null && !attendees.isEmpty()) {
                        if (attendees.size() == 1) {
                            Long id = attendees.get(0) != null ? attendees.get(0).getId() : 0;
                            attendee = getManager().loadAttendee(id);
                        } else {
                            message = messageSource.getMessage("parameters.multiple", null, Locale.getDefault());
                            addErrorMessage(message);
                            return "fail";
                        }
                    }
                } else {
                    message = messageSource.getMessage("parameters.required", null, Locale.getDefault());
                    addErrorMessage(message);
                    return "fail";
                }
            }
        }

        if (attendee != null) {
            return "success";
        } else {
            addInfoMessage("No se encontraron registros");
            return "fail";
        }
    }

    public String save() {
        if (attendee != null) {
            if (isBlank(attendee.getFirstName())) {
                addErrorMessage("Primer nombre es requerido");
                return "fail";
            }
            if (isBlank(attendee.getLastName())) {
                addErrorMessage("Primer apellido es requerido");
                return "fail";
            }
            if (isBlank(attendee.getEmail())) {
                addErrorMessage("Correo es requerido");
                return "fail";
            }
            if (attendee.getCategory() == null) {
                addErrorMessage("La categoria de participacion es requerida");
                return "fail";
            }
            if (attendee.getResidence() == null) {
                addErrorMessage("El pais de residencia es requerido");
                return "fail";
            }

            if (attendee.getCountry() != null && !attendee.getResidence().getName().equals("Nicaragua")) {
                if (attendee.isNeedDepartureTransportation()) {
                    if (attendee.getLodging() != null) {
                        if (attendee.getLodging().getDepartureDate() == null) {
                            addErrorMessage("Por favor informe la FECHA de salida");
                            return "fail";
                        }
                        if (attendee.getLodging().getDepartureTime() == null) {
                            addErrorMessage("Por favor informe la HORA de su salida");
                            return "fail";
                        }
                        if (attendee.getLodging().getTerminal() == null) {
                            addErrorMessage("Por favor informe la TERMINAL");
                            return "fail";
                        }
                    } else {
                        addErrorMessage("Por favor informe datos de su salida");
                        return "fail";
                    }
                }
                /*
                 if (attendee.getLodging().getHotel() == null) {
                 addErrorMessage("Por favor informe el lugar de hospedaje");
                 return "fail";
                 } 
                 */
            }
            //attendee.setMemberVerification(null);
            if (attendee.getMemberVerification() != null && attendee.getMemberVerification().equals(MemberVerification.PENDIENTE_VERIFICACION)) {
                if (attendee.getCategory().isRequiresValidation()) {
                    if (!isBlank(attendee.getMemberId())) {
                        member = getManager().loadMember(attendee.getMemberId());
                        if (member != null) {
                            attendee.setMemberVerification(MemberVerification.VERIFICADO);
                        }
                    }

                    if (attendee.getMemberVerification().equals(MemberVerification.PENDIENTE_VERIFICACION)) {
                        if (!isBlank(attendee.getVerificationCode()) && !isBlank(attendee.getCategory().getVerificationCodes())) {
                            boolean verificado = false;
                            String[] codes = attendee.getCategory().getVerificationCodes().split(",");
                            for (String code : codes) {
                                if (attendee.getVerificationCode().equals(code)) {
                                    verificado = true;
                                    attendee.setMemberVerification(MemberVerification.VERIFICADO_CON_CODIGO);
                                }
                            }
                            if (!verificado) {
                                message = messageSource.getMessage("verification.error", null, Locale.getDefault());
                                needVerificationCode = true;
                                addErrorMessage(message);
                                return "fail";
                            }
                        } else {
                            message = messageSource.getMessage("verification.error", null, Locale.getDefault());
                            needVerificationCode = true;
                            addErrorMessage(message);
                            return "fail";
                        }
                    }
                } else {
                    attendee.setMemberVerification(MemberVerification.NO_REQUIERE_VERIFICACION);
                }
            }
            String fullName = attendee.getFirstName() + " " + attendee.getMiddleName() + " " + attendee.getLastName() + " " + attendee.getSecondLastName();
            attendee.setFullName(fullName);

            if (attendee.getCategory() != null) {
                attendee.setCost(attendee.getCategory().getCost());
                attendee.setFinalCost(attendee.getCategory().getCost());
            }

            getManager().store(attendee);
            //getRequestMap().put("print", true);
            ((ConfirmationBean) lookup("confirmationBean")).startup(attendee);
        }
        return "success";
    }

    public String confirmStage() {
        attendee.setCurrentStage(Stage.PRESENTE);
        attendee.setConfirmationDate(new Date());
        getManager().store(attendee);
        return "success";
    }

    public Attendee getAttendee() {
        return attendee;
    }

    public void setAttendee(Attendee attendee) {
        this.attendee = attendee;
    }

    public String getSearchValue() {
        return searchValue;
    }

    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }

    public String getSearchType() {
        return searchType;
    }

    public void setSearchType(String searchType) {
        this.searchType = searchType;
    }

    public List<Country> getCountries() {
        return countries;
    }

    public void setCountries(List<Country> countries) {
        this.countries = countries;
    }

    public List<Category> getCategories() {
        return categories;
    }

    public void setCategories(List<Category> categories) {
        this.categories = categories;
    }

    public List<Hotel> getHotels() {
        return hotels;
    }

    public void setHotels(List<Hotel> hotels) {
        this.hotels = hotels;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getSecondLastName() {
        return secondLastName;
    }

    public void setSecondLastName(String secondLastName) {
        this.secondLastName = secondLastName;
    }

    public Member getMember() {
        return member;
    }

    public void setMember(Member member) {
        this.member = member;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean isNeedVerificationCode() {
        return needVerificationCode;
    }

    public void setNeedVerificationCode(boolean needVerificationCode) {
        this.needVerificationCode = needVerificationCode;
    }

    public List<Attendee> getHeads() {
        return heads;
    }

    public List<Attendee> getLeaders() {
        return leaders;
    }

    public List<PaymentMethod> getPaymentMethods() {
        return paymentMethods;
    }

    public void setPaymentMethods(List<PaymentMethod> paymentMethods) {
        this.paymentMethods = paymentMethods;
    }

    public List<RoomPlan> getRoomPlans() {
        return roomPlans;
    }

    public void setRoomPlans(List<RoomPlan> roomPlans) {
        this.roomPlans = roomPlans;
    }
}
